<template>
	<view class="wrap">
		<u-form class="form" :model="model" :rules="rules" ref="uForm" :label-position="labelPosition">
			<u-form-item label="标题" prop="title" label-width="180" :required="true">
				<u-input v-model="model.title" type="text" placeholder="请输入会议标题" maxlength="64" style="text-align: left;" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item label="开始时间" prop="startTime" label-width="180" :required="true">
				<view style="width: 100%;">
					<u-input v-model="model.startTime == ''?'请选择开始时间':model.startTime" :type="disabled?'input':'select'" @click="uPickerStartTime.show = !disabled" :disabled="disabled"></u-input>
					<u-picker v-model="uPickerStartTime.show" :mode="uPickerStartTime.mode" :params="uPickerStartTime.params" @confirm="confirm4StartTime"></u-picker>
				</view>
			</u-form-item>
			<u-form-item v-if="!showEndTime" label="持续时长" prop="meetingDuration" label-width="180" :required="true">
				<js-select v-model="meetingDuration" dict-type="wechat_living_duration" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择持续时长" :disabled="disabled" @input="durationChange"></js-select>
			</u-form-item>
			<u-form-item v-if="showEndTime" ref="uFormItemEndTime" label="结束时间" prop="endTime" label-width="180" :required="true">
				<view style="width: 100%;">
					<u-input v-model="model.endTime == ''?'请选择结束时间':model.endTime" :type="disabled?'input':'select'" @click="uPickerEndTime.show = !disabled" :disabled="disabled"></u-input>
					<u-picker v-model="uPickerEndTime.show" :mode="uPickerEndTime.mode" :params="uPickerEndTime.params" @confirm="confirm4EndTime"></u-picker>
				</view>
			</u-form-item>
			<u-form-item label="管理员" prop="adminName" label-width="180" :required="true">
				<u-input v-model="model.adminName" :type="disabled?'input':'select'" placeholder="请选择管理员" :disabled="disabled" @click="chooseAdmin"></u-input>
				<js-choose-user-popup v-if="useInitChooseUserComp" ref="chooseAdmin" @submit="useAdminSelected"
					:mode="popupAdmin.mode" :multiple="popupAdmin.multiple"
					:action="chooseUserUrl" :default-selected-user-list = "defaultAdminUserList"></js-choose-user-popup>
			</u-form-item>
			<u-form-item ref="uFormItemUserList" label="会议成员" prop="userList" label-width="180" label-position="top" :required="true">
				<view>
					<scroll-view :scroll-top="scrollTop" :scroll-y="scrollY" :class="{'scroll-Y': isScroll}"
						@scroll="scroll">
						<u-tag :text="item.name" :type="uTagProps.type" v-for="(item, index) in model.userList" 
							:key="item.userId" :index="item.userId" :shape="uTagProps.shape" 
							:closeable="uTagProps.closeable" :mode="uTagProps.mode" 
							:size="uTagProps.size" @close="doDeleteUser" class="uTagStyle"></u-tag>
					</scroll-view>
				</view>
				<u-button v-if="!isViewMode" slot="right" type="success" size="mini" @click="chooseGroupUsers" style="">选择成员</u-button>
				<js-choose-user-popup v-if="useInitChooseUserComp" ref="chooseGroupUsers" @submit="useGroupUsersSelected"
					:mode="popupMeetingUsers.mode" :multiple="popupMeetingUsers.multiple"
					:action="chooseUserUrl" :default-selected-user-list = "defaultGroupMemberUserList"></js-choose-user-popup>
			</u-form-item>
			<u-form-item label="会议描述" prop="description" label-width="180" label-position="top">
				<u-input v-model="model.description" type="textarea" placeholder="请输入会议的描述" height="100" maxlength="500" :disabled="disabled"/>
			</u-form-item>
			<u-form-item label="会议地点" prop="location" label-width="180">
				<u-input v-model="model.location" placeholder="请输入会议地点" type="text" maxlength="64" style="text-align: left;" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item label="入会密码" prop="password" label-width="180">
				<u-input v-model="model.password" placeholder="请输入入会密码，密码为4-6位数字" type="text" maxlength="64" style="text-align: left;" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item label="开启等候室" prop="enableWaitingRoom" label-width="180">
				<u-switch v-model="enableWaitingRoomChecked" active-value="1" inactive-value="0" @change="enableWaitingRoomChange" :disabled="disabled"></u-switch>
			</u-form-item>
			<u-form-item label="允许成员在主持人进会前加入" prop="allowEnterBeforeHost" label-width="auto">
				<u-switch v-model="allowEnterBeforeHostChecked" active-value="1" inactive-value="0" @change="allowEnterBeforeHostChange" :disabled="disabled"></u-switch>
			</u-form-item>
			<u-form-item label="来电提醒方式" prop="remindScope" label-width="180">
				<js-select v-model="model.remindScope" dict-type="wechat_remind_scope" itemLabel="dictValue"
					itemValue="dictKey" placeholder="会议开始时来电提醒方式" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item label="入会时静音" prop="enableEnterMute" label-width="180">
				<js-select v-model="model.enableEnterMute" dict-type="wechat_enable_enter_mute" itemLabel="dictValue"
					itemValue="dictKey" placeholder="成员入会时静音" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item label="入会成员类型" prop="allowExternalUser" label-width="180">
				<js-select v-model="model.allowExternalUser" dict-type="wechat_allow_external_user" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择入会成员类型" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item label="开启屏幕水印" prop="enableScreenWatermark" label-width="180">
				<u-switch v-model="enableScreenWatermarkChecked" active-value="1" inactive-value="0" @change="enableScreenWatermarkChange" :disabled="disabled"></u-switch>	
			</u-form-item>
			<u-form-item label="会议类型" prop="isRepeat" label-width="180">
				<js-select v-model="model.isRepeat" dict-type="wechat_is_repeat" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择会议类型" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item v-if="showRepeatType" label="会议重复类型" prop="repeatType" label-width="180">
				<js-select v-model="model.repeatType" dict-type="wechat_repeat_type" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择会议重复类型" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item label="提醒时间" prop="remindBefore" label-width="180">
				<u-checkbox-group @change="remindBeforeGroupChange" :width="checkboxGroupProps.width" :wrap="checkboxGroupProps.wrap" :disabled="disabled">
					<u-checkbox v-model="item.checked" v-for="(item, index) in dictDataOptions.wechatRemindBefore" :key="index" :name="item.value">{{ item.label }}</u-checkbox>
				</u-checkbox-group>	
			</u-form-item>
		</u-form>
		<slot name="footerBtns">
			<view style="display: flex;flex-direction: row;">
				<u-button v-if="!isViewMode" class="btn" style="width: 50%;margin-right: 10rpx;" type="primary" @click="submit">保存</u-button>
				<u-button class="btn" style="width: 50%;" @click="cancel">
					{{isViewMode ? '返回' : '取消'}}
				</u-button>
			</view>
		</slot>
	</view>
</template>
<script>
	/**
	 * @property {Stringr | Number} id 主键ID
	 * @property {Stringr} modeProp 模式（view、eidit、add）外部传入的属性
	 */
	export default {
		props: {
			id: {
				type: [String,Number],
				default: ''
			},
			modeProp: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				model: {
					title: '',
					startTime: '',
					endTime: '',
					adminName: '',
					adminUserid: '',
					userId: '',
					userList: [],
					description: '',
					location: '',
					enableWaitingRoom: '',
					allowEnterBeforeHost: '',
					remindScope: '',
					enableEnterMute: '',
					allowExternalUser: '',
					enableScreenWatermark: '',
					isRepeat: '',
					repeatType: '',
					remindBefore: ''
				},
				isModelLoadedFlag: false,
				// 操作模式：view、add、edit
				mode: '',
				meetingDuration: '',
				uPickerStartTime: {
					show: false,
					mode: 'time',
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true
					},
				},
				uPickerEndTime: {
					show: false,
					mode: 'time',
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true
					},
				},
				uTagProps: {
					mode: 'light',
					type: 'primary',
					size: 'default',
					shape: 'square',
					closeable: true
				},
				isViewMode: false,
				//是否显示结束时间表单项
				showEndTime: false,
				showRepeatType: false,
				labelPosition: 'left',
				disabled: true,
				rules: {
					title: [{
						required: true,
						message: '请输入会议标题',
						trigger: ['blur','change']
					}],
					startTime: [
						{
							required: true,
							message: '请选择开始时间',
							trigger: 'change'
						},
						{
							validator: (rule, value, callback) => {
								let startTime = new Date(value);
								let curTime = new Date();
								if(startTime.getTime() < curTime.getTime()){
									return false;
								}
								return true;
							},
							message: '开始时间不能小于当前时间',
							trigger: 'change'
						}
					],
					meetingDuration: [{
						validator: (rule, value, callback) => {
							// meetingDuration不是model对象的属性，所以value没有值
							let validateResult = true;
							let meetingDuration = this.meetingDuration;
							if(!this.showEndTime && !meetingDuration){
								validateResult = false;
							}
							return validateResult;
						},
						message: '请选择持续时长',
						trigger: 'change'
					}],
					endTime: [
						{
							required: true,
							message: '请选择结束时间',
							trigger: 'change',
						},
						{
							validator: (rule, value, callback) => {
								let endTime = new Date(value);
								if(this.model.startTime){
									let startTime = new Date(this.model.startTime);
									if(endTime.getTime() < startTime.getTime()){
										callback(new Error('结束时间不能小于开始时间'));
									}else{
										callback();
									}
								}else{
									callback(new Error('请先选择开始时间'));
								}
							},
							trigger: 'change'
						}
					],
					adminName: [{
						required: true,
						message: '请选择管理员',
						trigger: 'change',
					}],
					userList: [{
						required: true,
						message: '请选择会议成员',
						trigger: 'change',
						type: 'array'
					}, {
						validator: (rule, value, callback) => {
							let validateResult = value.some((user) => user.userId == this.model.adminUserid);
							if (validateResult) {
								callback();
							} else {
								callback(new Error('管理员必须在会议成员内'));
							}
						},
						trigger: 'change'
					}]
				},
				labelPosition: 'left',
				chooseUserUrl: '/api/blade-system/user/user-list-by-dept-type',
				popupAdmin: {
					show: false,
					mode: "bottom",
					multiple: false,
				},
				popupMeetingUsers: {
					show: false,
					mode: "bottom",
					multiple: true,
				},
				isScroll: true,
				scrollTop: 0,
				scrollY: true,
				old: {
					scrollTop: 0
				},
				checkboxGroupProps: {
					width: 'auto',
					wrap: false
				},
				dictDataOptions: {
					'wechatRemindBefore': []
				},
				enableWaitingRoomChecked: false,
				allowEnterBeforeHostChecked: false,
				enableScreenWatermarkChecked: false
			};
		},
		computed: {
			/**
			 * 返回是否初始化选择用户组件的标识
			 * 解决父组件将请求回来的数据传递给子组件的延迟问题
			 */
			useInitChooseUserComp: function(){
				let useInit = false;
				if(this.mode === 'add' || (this.mode === 'edit' && this.isModelLoadedFlag)){
					useInit = true;
				}
				return useInit;
			},
			defaultAdminUserList: function(){
				let userList = [];
				if(this.model.adminUserid){
					userList.push({
						id: this.model.adminUserid,
						name: this.model.adminName
					});
				}
				return userList;
			},
			defaultGroupMemberUserList: function(){
				let userList = this.model.userList.map(user => {
					return {
						id: user.userId,
						name: user.name,
					}
				});
				return userList;
			}
		},
		watch: {
			'model.userList': function(val,oldVal){
				// 通知将当前的值发送到 userList的u-form-item组件中进行校验
				this.$refs.uFormItemUserList.$emit('on-form-change', val);
			},
			'model.isRepeat': function(val,oldVal){
				if(val == '1'){
					this.showRepeatType = true;
				}else if(val == '0'){
					this.showRepeatType = false;
				}
			},
			'model.startTime': function(val,oldVal){
				if(val && this.$refs.uFormItemEndTime){
					this.$refs.uFormItemEndTime.$emit('on-form-change');
				}
			},
			'model.enableWaitingRoom': function(val, oldVal) {
				if (val == 1) {
					this.enableWaitingRoomChecked = true;
				} else {
					this.enableWaitingRoomChecked = false;
				}
			},
			'model.allowEnterBeforeHost': function(val, oldVal) {
				if (val == 1) {
					this.allowEnterBeforeHostChecked = true;
				} else {
					this.allowEnterBeforeHostChecked = false;
				}
			},
			'model.enableScreenWatermark': function(val, oldVal) {
				if (val == 1) {
					this.enableScreenWatermarkChecked = true;
				} else {
					this.enableScreenWatermarkChecked = false;
				}
			}
		},
		beforeCreate(){
			// console.log("0.beforeCreate...");
		},
		onLoad(params) {
			// console.log("1.onLoad...");
			this.initData(params);
		},
		created() {
			// console.log("2.created...");
			if(this.id){
				// 场景适用于当前组件在弹出层中的展示
				let params = {
					id: this.id
				};
				if(this.modeProp){
					params.mode = this.modeProp;
				}
				this.initData(params);
			}
		},
		onReady() {
			// console.log("3.onReady...");
			this.$refs.uForm.setRules(this.rules);
		},
		beforeMount(){
			// console.log("beforeMount...");
		},
		mounted(){
			// console.log("4.mounted...");
		},
		methods: {
			initData(params){
				let vm = this;
				this.mode = params.mode;
				if (params.id) {
					this.showEndTime = true;
					if (this.mode == "view") {
						this.disabled = true;
						this.isViewMode = true;
						this.uTagProps.closeable = false;
					} else {
						this.disabled = false;
						this.isViewMode = false;
						this.uTagProps.closeable = true;
					}
					this.$u.api.wechat.wechatMeeting.detail({
						id: params.id
					}).then(res => {
						Object.assign(vm.model, res.data);
						vm.isModelLoadedFlag = true;
						//方法initData与initWechatRemindBefore异步情况
						vm.initWechatRemindBefore();
					});
				} else {
					this.disabled = false;
					this.showEndTime = false;
					// 新增时默认开启允许成员在主持人进会前加入
					this.model.allowEnterBeforeHost = '1';
					vm.initWechatRemindBefore();
				}
			},
			durationChange(val){
				//自定义时间
				if(val == 4){
					this.model.endTime = '';
					this.showEndTime = true;
					//将回调延迟到下次 DOM 更新循环之后执行
					this.$nextTick(() => {
						if(this.$refs.uFormItemEndTime){
							this.$refs.uFormItemEndTime.$emit('on-form-change')
						}
					});
				}
			},
			initWechatRemindBefore(){
				let vm = this;
				this.$u.api.dictBizData({
					code: 'wechat_remind_before'
				}).then(res => {
					let dictDataList = [];
					let remindBefore2Array = [];
					if(vm.model.remindBefore){
						remindBefore2Array = vm.model.remindBefore.split(',');
					}
					res.data.forEach((item) => {
						let checked = remindBefore2Array.some(element => element == item.dictKey);
						dictDataList.push({
							'label': item.dictValue,
							'value': item.dictKey,
							'checked': checked
						});
					})
					this.dictDataOptions.wechatRemindBefore = dictDataList;
				});
			},
			getPickerResult(e,params){
				let pickerResult = '';
				if (params.year) {
					pickerResult += e.year;
				}
				if (params.month) {
					pickerResult += '-' + e.month;
				}
				if (params.day) {
					pickerResult += '-' + e.day;
				}
				if (params.hour) {
					pickerResult += ' ' + e.hour;
				}
				if (params.minute) {
					pickerResult += ':' + e.minute;
				}
				if (params.second) {
					pickerResult += ':' + e.second;
				}
				return pickerResult;
			},
			confirm4StartTime(e) {
				this.model.startTime = this.getPickerResult(e,this.uPickerStartTime.params);
				this.uPickerStartTime.show = false;
			},
			confirm4EndTime(e) {
				this.model.endTime = this.getPickerResult(e,this.uPickerEndTime.params);
				this.uPickerEndTime.show = false;
			},
			chooseAdmin() {
				if(this.disabled){
					return;
				}
				this.$refs.chooseAdmin.open();
				this.$refs.chooseAdmin.setDefaultSelectedUserList(this.defaultAdminUserList);
			},
			useAdminSelected() {
				let groupAdminArr = this.$refs.chooseAdmin.getData();
				if (groupAdminArr.length > 0) {
					let groupAdmin = groupAdminArr[0];
					this.model.adminUserid = groupAdmin.id;
					this.model.adminName = groupAdmin.name;
				}
				this.$refs.chooseAdmin.close();
			},
			chooseGroupUsers() {
				this.$refs.chooseGroupUsers.open();
				this.$refs.chooseGroupUsers.setDefaultSelectedUserList(this.defaultGroupMemberUserList);
			},
			useGroupUsersSelected() {
				let groupUsers = this.$refs.chooseGroupUsers.getData();
				if (groupUsers.length > 0) {
					this.model.userList = [];
				}
				groupUsers.forEach((element) => {
					this.model.userList.push({
						"name": element.name,
						"userId": element.id
					});
				});
				this.$refs.chooseGroupUsers.close();
			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			doDeleteUser: function(userId) {
				this.model.userList = this.model.userList.filter(user => userId != user.userId);
				this.$refs.chooseGroupUsers.$emit('remove-selected-user-by-id',userId);
			},
			doBeforeModelPost: function(){
				if(!this.showEndTime){
					//根据持续时长计算结束时间
					let startTime = new Date(this.model.startTime);
					let secondsOfEndTime = startTime.setSeconds(startTime.getSeconds() + parseInt(this.meetingDuration));
					this.model.endTime = this.$u.timeFormat(secondsOfEndTime,'yyyy-mm-dd hh:MM:ss');
				}
				if(this.model.userList.length > 0){
					let userIds = this.model.userList.map(user => user.userId);
					this.model.userId = userIds.join(',');
				}
			},
			enableWaitingRoomChange(value) {
				this.model.enableWaitingRoom = value;
			},
			allowEnterBeforeHostChange(value) {
				this.model.allowEnterBeforeHost = value;
			},
			enableScreenWatermarkChange(value) {
				this.model.enableScreenWatermark = value;
			},
			remindBeforeGroupChange(e){
				this.model.remindBefore = e.join(',');
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading({
							title: '提交中....'
						})
						this.doBeforeModelPost();
						let promise = null;
						if(this.mode == 'edit'){
							promise = this.$u.api.wechat.wechatMeeting.edit(this.model)
						}else{
							promise = this.$u.api.wechat.wechatMeeting.save(this.model);
						}
						promise.then(res => {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false,
								success: function() {
									if (res.code == 200) {
										uni.setStorageSync('refreshWecahtMeetingList', true);
										uni.navigateBack();
									}
								}
							});
						});
					} else {
						this.$u.toast('您填写的信息有误，请根据提示修正。');
					}
				});
			},
			cancel() {
				uni.navigateBack();
			},
		}
	};
</script>
<style lang="scss" scoped>
	.wrap {
		padding: 30rpx;
	}

	.uTagStyle {
		margin-right: 10rpx;
	}

	.scroll-Y {
		height: 200rpx;
	}

	/deep/ ::-webkit-scrollbar {
		/*滚动条整体样式*/
		width: 4px !important;
		height: 1px !important;
		overflow: auto !important;
		background: #ccc !important;
		-webkit-appearance: auto !important;
		display: block;
	}

	/deep/ ::-webkit-scrollbar-thumb {
		/*滚动条里面小方块*/
		border-radius: 10px !important;
		box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		background: #7b7979 !important;
	}

	/deep/ ::-webkit-scrollbar-track {
		/*滚动条里面轨道*/
		background: #FFFFFF !important;
	}
</style>